module.exports = app => {
    const experss = require("express")
    const assert = require("http-assert")
    const jwt = require("jsonwebtoken")
    const AdminUser = require("../../models/AdminUser")
    //这是子路由 用于单一页面的数据增删改查 实施其中逻辑后 挂载到 app 上 
    const router = experss.Router({
        mergeParams: true
    })

   
    // 引用创建好的模型
    // const Category = require("../../models/Category")


    // 判断用户是否登录的中间件
    const authMiddleware = require("../../middleware/auth")

    // 用户资源路径的中间件
    const resourceMiddleware = require("../../middleware/resource")

    // 创建分类
    router.post("/", async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 修改分类
    router.put("/:id", async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 分类列表 
    router.get("/",async (req, res) => {
        const queryOptions = {}
        if (req.Model.modelName === "Category") {
            queryOptions.populate = "parent"
        }
        const items = await req.Model.find().setOptions(queryOptions).limit(300)
        res.send(items)
    })

    // 编辑列表
    router.get("/:id", async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })

    // 删除分类
    router.delete("/:id", async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id, req.body)
        console.log("ok")
        res.send({
            success: true
        })
    })
    // 定义通用接口
    app.use("/admin/api/rest/:resource",authMiddleware(),resourceMiddleware(),router)
    // app.use("/admin/api/rest/:resource",resourceMiddleware(),router)




    // 定义上传文件的接口
    const multer = require("multer")
    const upload = multer({
        dest: __dirname + "/../../uploads"
    })
    app.post("/admin/api/upload",upload.single('file'), async (req, res) => {
        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })





    // 登录路由
    app.post("/admin/api/login", async (req, res) => {

        // 根据用户名找用户
        
        const user = await AdminUser.findOne({
            username: req.body.username
        }).select("+password")
        assert(user,422,"用户不存在")
        //  校验密码
        const isVaild = require("bcryptjs").compareSync(
            req.body.password,
            user.password
        )
        assert(isVaild,422,"密码错误")
        // 返回tooken
       
        const token = jwt.sign({
            id: user._id,
        },app.get("secret"))
        res.send(token)
    })



    // 错误处理
    app.use(async (err,req,res,next) =>{
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}